package xin.marcher.module.rights.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.common.core.PageResult;
import xin.marcher.module.rights.domain.dto.UserDTO;
import xin.marcher.module.rights.domain.request.ModifyPasswordRequest;
import xin.marcher.module.rights.domain.request.QueryUserRequest;
import xin.marcher.module.rights.domain.request.RemoveUserRequest;
import xin.marcher.module.rights.domain.request.UserRequest;
import xin.marcher.module.rights.repository.LoginRepository;
import xin.marcher.module.rights.repository.RightsRepository;
import xin.marcher.module.rights.service.UserService;

import java.util.Objects;

/**
 *
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RightsRepository rightsRepository;

    @Autowired
    private LoginRepository loginRepository;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    @Transactional
    public JsonResult saveUser(UserRequest request) {
        // 校验用户名
        UserDTO userDTO = rightsRepository.queryUserByUsername(request.getUsername());
        if (Objects.nonNull(userDTO)) {
            return JsonResult.buildError("用户名已存在");
        }
        // 保存用户
        Long userId = rightsRepository.saveUser(request);
        // 保存用户关联的角色
        rightsRepository.saveUserRoleRelation(userId, request);
        return JsonResult.buildSuccess();
    }

    @Override
    @Transactional
    public void removeUser(RemoveUserRequest request) {
        // 删除用户和角色的关联关系
        rightsRepository.removeUserRoleRelationByUserId(request.getUserId());
        // 删除用户
        rightsRepository.removeUser(request);
    }

    @Override
    public PageResult<UserDTO> queryUser(QueryUserRequest request) {
        return rightsRepository.queryUser(request);
    }

    @Override
    public JsonResult modifyPassword(ModifyPasswordRequest request) {
        UserDTO userDTO = rightsRepository.queryUserById(request.getUserId());
        if (Objects.isNull(userDTO)) {
            return JsonResult.buildError("用户不存在");
        }
        boolean matches = bCryptPasswordEncoder.matches(request.getOldPassword(), userDTO.getPassword());
        if (!matches) {
            return JsonResult.buildError("旧密码错误");
        }

        String encodedPassword = bCryptPasswordEncoder.encode(request.getNewPassword());
        if (rightsRepository.modifyPassword(request.getUserId(), encodedPassword)) {
            // 清除登录信息
            loginRepository.invalidteLoginInfo(request.getToken());
            return JsonResult.buildSuccess();
        }
        return JsonResult.buildError("修改密码失败");
    }
}
